package com.jerry.walking.module.activityTravel.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jerry.walking.R;
import com.jerry.walking.base.BaseApplication;
import com.jerry.walking.base.BaseFragment;
import com.jerry.walking.base.BaseViewHolder;
import com.jerry.walking.base.MyBaseAdapter;
import com.jerry.walking.constant.Urls;
import com.jerry.walking.module.activityTravel.activity.FirstActivity;
import com.jerry.walking.module.activityTravel.bean.TravelLive1;
import com.jerry.walking.utils.OkHttpUtils;
import com.jerry.walking.views.ExpandGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Yang on 2016/5/10.
 *
 *          直播  fragment 主界面
 */
public class LiveFragment extends BaseFragment{

    @BindView(R.id.lv_travel_live_1)
    PullToRefreshListView listView;

    private MyBaseAdapter<TravelLive1.BroadcastsBean> adapter;

    //页数设置
    private int page;

    //将加载数据放置此集合中
    private List<TravelLive1.BroadcastsBean> items;

    private ImageLoader imageLoader;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_live;
    }

    @Override
    protected void initViews() {
        super.initViews();

        imageLoader = BaseApplication.getApplication().getImageLoader();

        //设置listview的刷新模式
        listView.setMode(PullToRefreshBase.Mode.BOTH);

        //初始化
        items = new ArrayList<>();

        adapter = new MyBaseAdapter<TravelLive1.BroadcastsBean>(LiveFragment.this.getActivity(), items) {
            @Override
            public int getLayoutId() {
                return R.layout.adapter_travel_live;
            }

            @Override
            public BaseViewHolder getViewHolder() {
                return new ViewHolder();
            }

            @Override
            public void bindViews(View view, BaseViewHolder viewHolder) {
                final ViewHolder holder = (ViewHolder) viewHolder;

                //第一层加载
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .cacheOnDisk(true)
                        .cacheInMemory(true)
                        .imageScaleType(ImageScaleType.EXACTLY)
                        .build();
                imageLoader.displayImage(getItem(holder.position).getData().getLog().getCreated_by().getAvatar(), holder.imageView1, options);

                holder.textView1.setText(getItem(holder.position).getData().getLog().getCreated_by().getNickname());
                holder.textView2.setText("最近更新了"+getItem(holder.position).getData().getLog().getAdded_post_count()+"张照片");

                String created_date = getItem(holder.position).getData().getLog().getCreated_date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(new Date(Long.parseLong(created_date)));
                holder.textView3.setText(format);

                //图片加载
                // linearLayout1 来判断是否会显示多余图片按钮
                //需要判断来选择性的放置图片和多余控件
                int size = getItem(holder.position).getData().getLog().getPosts().size();

                MyAdapter gridViewAdapter = null;
                List<ImageView> imageViews = new ArrayList<>();
                if (size <= 0) {
                    holder.linearLayout1.setVisibility(View.GONE);
                }
                else if (size == 1) {
                    holder.gridView.setNumColumns(1);
                    ImageView imageView = new ImageView(LiveFragment.this.getActivity());
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                    String height = getItem(holder.position).getData().getLog().getPosts().get(0).getPictures().get(0).getHeight();
                    AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT);
                    imageView.setLayoutParams(params);
                    imageLoader.displayImage(getItem(holder.position).getData().getLog().getPosts().get(0).getPictures().get(0).getPicture(), imageView, options);
                    //设置图片大小

                    imageViews.add(imageView);

                    //设置图片适配器
                    gridViewAdapter = new MyAdapter(imageViews);
                    holder.gridView.setAdapter(gridViewAdapter);
                    holder.linearLayout1.setVisibility(View.GONE);
                }
                else if (size < 9) {
                    holder.gridView.setNumColumns(3);
                    ImageView imageView = null;
                    for (int i = 0; i < size; i++) {
                        imageView = new ImageView(LiveFragment.this.getActivity());
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                        imageLoader.displayImage(getItem(holder.position).getData().getLog().getPosts().get(i).getPictures().get(0).getPicture(), imageView, options);
                        //设置图片大小
                        AbsListView.LayoutParams params = new AbsListView.LayoutParams(480, 480);
                        imageView.setLayoutParams(params);
                        imageViews.add(imageView);
                    }
                    gridViewAdapter = new MyAdapter(imageViews);
                    holder.gridView.setAdapter(gridViewAdapter);

                    holder.linearLayout1.setVisibility(View.GONE);
                }
                else {
                    holder.gridView.setNumColumns(3);
                    ImageView imageView = null;
                    for (int i = 0; i < 9; i++) {
                        imageView = new ImageView(LiveFragment.this.getActivity());
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

                        imageLoader.displayImage(getItem(holder.position).getData().getLog().getPosts().get(i).getPictures().get(0).getPicture(), imageView, options);
                        //设置图片大小
                        AbsListView.LayoutParams params = new AbsListView.LayoutParams(480, 480);
                        imageView.setLayoutParams(params);

                        imageViews.add(imageView);
                    }
                    gridViewAdapter = new MyAdapter(imageViews);
                    holder.gridView.setAdapter(gridViewAdapter);

                    holder.linearLayout1.setVisibility(View.VISIBLE);
                }

                //设置标题
                String name = getItem(holder.position).getData().getLog().getName();
                if (TextUtils.isEmpty(name)) {
                    holder.linearLayout2.setVisibility(View.GONE);
                } else {
                    holder.textView4.setText(name);
                    holder.linearLayout2.setVisibility(View.VISIBLE);

                }

                //设置心得
                if(size <= 0) {
                    holder.linearLayout3.setVisibility(View.GONE);
                } else {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < size; i++) {
                        String description = getItem(holder.position).getData().getLog().getPosts().get(i).getDescription();
                        if (!TextUtils.isEmpty(description)) {
                            stringBuilder.append(description);
                        }
                    }

                    if (TextUtils.isEmpty(stringBuilder.toString())) {
                        holder.linearLayout3.setVisibility(View.GONE);
                    } else {
                        holder.textView5.setText(stringBuilder.toString());
                        holder.linearLayout3.setVisibility(View.VISIBLE);
                    }
                }

                //设置定位

                //设置手势
                holder.textView7.setText(getItem(holder.position).getData().getLog().getFav_count());

                //------监听器------

                //用户头像点击
                holder.imageView1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //TODO 用户头像点击
                        Log.d("--->", "OK");
                    }
                });

                //用户头像点击
                holder.textView1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //TODO 用户头像点击
                        Log.d("--->", "OK");
                    }
                });

                //用户改标题跳转
                holder.textView4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(LiveFragment.this.getActivity(), FirstActivity.class);
                        intent.putExtra("id", items.get(holder.position).getData().getLog().getId()+"");
                        LiveFragment.this.startActivity(intent);
                    }
                });

                //图片点击事件
                holder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                        Intent intent = new Intent(LiveFragment.this.getActivity(), FirstActivity.class);
                        intent.putExtra("id", items.get(holder.position).getData().getLog().getId()+"");
                        LiveFragment.this.startActivity(intent);
                    }
                });

            }

        };
        listView.setAdapter(adapter);

        //上下拉刷新加载
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                items.clear();
                page = 1;
                listView.setMode(PullToRefreshBase.Mode.BOTH);
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                loadData();
            }
        });

    }

    @Override
    protected void loadData() {
        super.loadData();

        //数据下载
        OkHttpUtils.get(Urls.LIVE_LIST + page, new OkHttpUtils.OnGetDataListener() {
            @Override
            public void onResponse(String url, String data) {
                //data 为数据源
                //url 为传输的最终url
                Log.d("--->url", url+"/n"+data);
                Gson gson = new Gson();

                TravelLive1 travelLive1 = gson.fromJson(data, TravelLive1.class);

                List<TravelLive1.BroadcastsBean> broadcasts = travelLive1.getBroadcasts();

                //显示最后一页特殊处理
                if (travelLive1.getCur_page() == travelLive1.getTotal_pages()) {
//                    Toast.makeText(LiveFragment.this.getActivity(), "已加载至最后一页", Toast.LENGTH_SHORT).show();
                    listView.onRefreshComplete();
                    listView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);//修改模式只允许下拉刷新
                }
//                items.clear();
                items.addAll(broadcasts);
                adapter.notifyDataSetChanged();
                listView.onRefreshComplete();
            }

            @Override
            public void onFailure(String url, String error) {
//                Toast.makeText(LiveFragment.this.getActivity(), "数据加载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 该类提供listview适配器中的所有资源id
     *
     */
    class ViewHolder extends BaseViewHolder{
        @BindView(R.id.iv_travel_live_adapter_head)
        ImageView imageView1; // 头像
        @BindView(R.id.tv_travel_live_adapter)
        TextView textView1;  // 名字
        @BindView(R.id.tv_travel_live_adapter2)
        TextView textView2;  // 最近消息
        @BindView(R.id.tv_travel_live_adapter3)
        TextView textView3;  // 日期

        @BindView(R.id.ll_travel_live_adapter)
        LinearLayout linearLayout1;
        @BindView(R.id.gv_travel_live_adapter)
        ExpandGridView gridView;  // 旅游图片

        @BindView(R.id.ll_travel_live_adapter1)
        LinearLayout linearLayout2;
        @BindView(R.id.tv_travel_live_adapter5)
        TextView textView4;  // 标题

        @BindView(R.id.ll_travel_live_adapter2)
        LinearLayout linearLayout3;
        @BindView(R.id.tv_travel_live_adapter6)
        TextView textView5;  // 心得

        @BindView(R.id.ll_travel_live_adapter3)
        LinearLayout linearLayout4;
        @BindView(R.id.tv_travel_live_adapter7)
        TextView textView6;  // 定位

        @BindView(R.id.tv_travel_live_adapter8)
        TextView textView7;
    }

    /**
     * 该类提供了listview中需要显示gridview中的数据的适配器
     */
    class MyAdapter extends BaseAdapter {

        private List<ImageView> list;

        public MyAdapter(List<ImageView> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (list.size() == 1) {
                return list.get(0);
            }
            return list.get(position);
        }
    }

}
